import { describe } from '$lib';
import { cleanup } from '$lib/cleanup';
import { removeEntity, type Entity, type IWorld, type Component, hasComponent } from '$lib/ecs';
import { logVisible } from '$lib/render3';
import { Global, getClock } from './clock';
import { Player } from './player';

type Drop = {
  target: Component,
  drop: (world: IWorld, e: Entity) => void,
};

const corpseDrop = new Map<Component, Drop>();

export const registerCorpseDrop = (drop: Drop) => {
  corpseDrop.set(drop.target, drop);
};

export const creatureDies = (world: IWorld, e: Entity) => {
  const isPlayer = hasComponent(world, Player, e);
  logVisible(e, `${describe(world, e)} dies`);
  for (let [component, drop] of corpseDrop) {
    if (hasComponent(world, component, e)) {
      drop.drop(world, e);
    }
  }
  if (isPlayer) {
    const clock = getClock(world);
    Global.gameOver[clock] = 1;
  } else {
    cleanup(world, e);
    removeEntity(world, e);
  }
};
